import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Progress, Typography, Spin, Tag, Button, Tooltip } from 'antd';
import { 
  BookOutlined, 
  ClockCircleOutlined, 
  CheckCircleOutlined,
  FireOutlined,
  CalendarOutlined,
  TrophyOutlined
} from '@ant-design/icons';
import { statisticsService } from '../services/api';

const { Title, Text } = Typography;

interface Habit {
  id: number;
  habit_name: string;
  habit_description: string;
  target_frequency: string;
  target_count: number;
  current_streak: number;
  longest_streak: number;
  total_completed: number;
  is_active: boolean;
  total_records: number;
  completed_records: number;
  last_record_date: string;
}

const HabitsSection: React.FC = () => {
  const [habits, setHabits] = useState<Habit[]>([]);
  const [loading, setLoading] = useState(false);

  const loadHabits = async () => {
    setLoading(true);
    try {
      const response = await statisticsService.getHabits();
      if ((response as any).success) {
        setHabits((response as any).data);
      }
    } catch (error) {
      console.error('加载学习习惯失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadHabits();
  }, []);

  const getFrequencyText = (frequency: string) => {
    switch (frequency) {
      case 'daily':
        return '每日';
      case 'weekly':
        return '每周';
      case 'monthly':
        return '每月';
      default:
        return frequency;
    }
  };

  const getStreakColor = (streak: number) => {
    if (streak >= 30) return '#f50';
    if (streak >= 7) return '#fa8c16';
    if (streak >= 3) return '#52c41a';
    return '#1890ff';
  };

  const getStreakText = (streak: number) => {
    if (streak >= 30) return '传奇';
    if (streak >= 7) return '大师';
    if (streak >= 3) return '达人';
    return '新手';
  };

  const getCompletionRate = (completed: number, total: number) => {
    if (total === 0) return 0;
    return Math.round((completed / total) * 100);
  };

  if (loading) {
    return (
      <Card title="学习习惯" extra={<BookOutlined />}>
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Spin size="large" />
        </div>
      </Card>
    );
  }

  return (
    <Card title="学习习惯" extra={<BookOutlined />}>
      {habits.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Text type="secondary">暂无学习习惯，开始培养好习惯吧！</Text>
        </div>
      ) : (
        <Row gutter={[16, 16]}>
          {habits.map((habit) => (
            <Col xs={24} lg={12} key={habit.id}>
              <Card
                size="small"
                style={{
                  border: habit.is_active ? '1px solid #d9d9d9' : '1px solid #f0f0f0',
                  background: habit.is_active ? '#ffffff' : '#fafafa'
                }}
              >
                <div style={{ marginBottom: '12px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                    <Text strong style={{ color: habit.is_active ? '#1890ff' : '#8c8c8c' }}>
                      {habit.habit_name}
                    </Text>
                    <Tag color={habit.is_active ? 'blue' : 'default'}>
                      {getFrequencyText(habit.target_frequency)}
                    </Tag>
                  </div>
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    {habit.habit_description}
                  </Text>
                </div>

                <div style={{ marginBottom: '12px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                    <Text style={{ fontSize: '12px' }}>完成率</Text>
                    <Text style={{ fontSize: '12px' }}>
                      {getCompletionRate(habit.completed_records, habit.total_records)}%
                    </Text>
                  </div>
                  <Progress
                    percent={getCompletionRate(habit.completed_records, habit.total_records)}
                    size="small"
                    strokeColor={habit.is_active ? '#1890ff' : '#d9d9d9'}
                  />
                </div>

                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <Tooltip title="当前连续天数">
                      <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                        <FireOutlined style={{ color: getStreakColor(habit.current_streak) }} />
                        <Text style={{ color: getStreakColor(habit.current_streak), fontSize: '12px' }}>
                          {habit.current_streak}天
                        </Text>
                      </div>
                    </Tooltip>
                    <Tag color={getStreakColor(habit.current_streak)} style={{ fontSize: '10px' }}>
                      {getStreakText(habit.current_streak)}
                    </Tag>
                  </div>
                  
                  <div style={{ textAlign: 'right' }}>
                    <Text style={{ fontSize: '12px', color: '#8c8c8c' }}>
                      总计: {habit.total_completed}次
                    </Text>
                  </div>
                </div>

                {habit.last_record_date && (
                  <div style={{ marginTop: '8px', textAlign: 'right' }}>
                    <Text style={{ fontSize: '11px', color: '#8c8c8c' }}>
                      最后记录: {new Date(habit.last_record_date).toLocaleDateString()}
                    </Text>
                  </div>
                )}
              </Card>
            </Col>
          ))}
        </Row>
      )}
    </Card>
  );
};

export default HabitsSection;
